﻿using System;
using System.Collections.Generic;
using System.Linq;
using SalesSys.BLL;
using SalesSys.Comm.Utility;
using SalesSys.DAL.Models;
using FluentScheduler;
using Jiguang.JPush;
using System.Collections;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.AspNet.SignalR;
using System.Web;
using SalesSys.WebCore.Authorize;

namespace SalesSys.WebCore
{

     
    public class PushSms
    {
        private static DateTime? LastMsgTime;
        private static DateTime? LastPhoneMsgTime;
        NoticeInfoBLL entityBLL = BLL.BllFactory.GetBll<NoticeInfoBLL>();
        private EmployeeBLL empBll = new EmployeeBLL();
        private ChinaSms sms = new ChinaSms("中伟钢物联", "zwgwl2014");
        PhoneLogBLL phoneLogBLL = BLL.BllFactory.GetBll<PhoneLogBLL>();
        public void Push()
        {
            if (LastPhoneMsgTime == null)
            {
                var lastMsg = phoneLogBLL.GetPaging(null, p => p.OperaTime, true, 1, 1).Value;
                if (lastMsg.Any())
                {
                    LastPhoneMsgTime = lastMsg.First().OperaTime;
                    return;
                }
            }
            SmsPush();
        }

        private  bool SmsPush()
        {
            var data = phoneLogBLL.GetPushMsg(LastPhoneMsgTime.Value, 10).OrderBy(p => p.OperaTime);
            if (data.Any())
            {
                foreach (var info in data) 
                {
                    LastPhoneMsgTime = info.OperaTime;

                    return sms.SingleSend(info.ToPhone, info.OperaMessage);
                }
            }
            return false;
        }
    }
    public class PushJPush 
    {
        JPushClient client = new JPushClient("e2b3142c6a2de3f867e50c7d", "2c67c2d672b22e859ab34ef9");
        private static DateTime? LastMsgTime;
        private static DateTime? LastPhoneMsgTime;
        NoticeInfoBLL entityBLL = BLL.BllFactory.GetBll<NoticeInfoBLL>();
        private EmployeeBLL empBll = new EmployeeBLL();
        private ChinaSms sms = new ChinaSms("中伟钢物联", "zwgwl2014");
        PhoneLogBLL phoneLogBLL = BLL.BllFactory.GetBll<PhoneLogBLL>();
        public void Push()
        {

            if (LastMsgTime == null)
            {
                var lastMsg = entityBLL.GetPaging(null, p => p.CreateTime, true, 1, 1).Value;
                if (lastMsg.Any())
                {
                    LastMsgTime = lastMsg.First().CreateTime;
                    return;
                }
            }
            SmsPush();
        }
        private void SmsPush()
        {
            var data = entityBLL.GetPushMsg(LastMsgTime.Value, 10).OrderBy(p => p.CreateTime);

            if (data.Any())
            {
                foreach (var info in data) //todo 应批量处理
                {
                    LastMsgTime = info.CreateTime;
                    if (info.To != default(Guid))
                    {
                        SendEmp(info);
                    }
                    if (!string.IsNullOrWhiteSpace(info.ToRoles) && info.ToRoles.Trim() != "|")
                    {
                        SendRole(info);
                    }
                }
            }
        }

        private void SendRole(NoticeInfo info)
        {
            var empList = empBll.GetList(p => p.Roles.Contains(info.ToRoles));
            Send(info, empList);
        }

        private void SendEmp(NoticeInfo info)
        {
            var emp = empBll.Details(info.To);
            Send(info, emp);
        }
        public virtual bool Send(NoticeInfo info, params Employee[] emps)
        {

            if (emps == null)
            {
                return false;
            }
            if (emps.Length == 1)
            {

                if (!string.IsNullOrWhiteSpace(emps[0].Phone))
                {
                    return sms.SingleSend(emps[0].Phone, info.Content);
                }
                return false;
            }
            var arr = emps.Where(p => !string.IsNullOrWhiteSpace(p.Phone)).Select(p => p.Phone).ToArray();
            if (arr.Length <= 0)
            {
                return false;
            }
            var re = string.Join(",", arr);


            return sms.SingleSend(re, info.Content);
        }
    }
    public class ChinaSms
    {
        private string comName;
        private string comPwd;

        public ChinaSms(String name, String pwd)
        {
            comName = System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.GetEncoding("gb2312"));
            this.comPwd = pwd;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="dst">手机号</param>
        /// <param name="msg">内容</param>
        /// <returns>是否成功</returns>
        public bool SingleSend(String dst, String msg)
        {
            msg = System.Web.HttpUtility.UrlEncode(msg, System.Text.Encoding.GetEncoding("gb2312"));
            var sUrl = "http://www.139000.com/send/gsend.asp?name=" + comName + "&pwd=" + comPwd + "&dst=" + dst +
                       "&msg=" +
                       msg;
            Log.m.d("调用短信接口："+sUrl);
            var sMsg = GetUrl(sUrl);
            Console.WriteLine(sMsg);
            var re = sMsg != null && sMsg.Substring(0, 5) != "num=0";
            if (!re)
            {
                Log.m.i("发送失败:手机号：{0};内容：{1};返回信息:{2}", dst, msg, sMsg);
            }
            return re;

        }

        /*通用调用接口*/

         String GetUrl(String urlString)
        {
            string sMsg = ""; //引用的返回字符串
            try
            {
                System.Net.HttpWebResponse rs =
                    (System.Net.HttpWebResponse)System.Net.HttpWebRequest.Create(urlString).GetResponse();
                System.IO.StreamReader sr = new System.IO.StreamReader(rs.GetResponseStream(),
                    System.Text.Encoding.Default);
                sMsg = sr.ReadToEnd();
                
            }
            catch(Exception ex)
            {
                Log.m.d("短信发送异常：Url="+urlString+";异常消息："+ex);
                return sMsg;
            }
            return sMsg;
        }
    }

    public class WebJobReg : Registry
    {
        readonly int interval = 15;
        //启动推送消息任务
        private PushJPush PushJPush = new PushJPush();
        //启动手机发送短信任务
        private PushSms pushSms = new PushSms();

        public WebJobReg()
        {
          
            Log.m.d("任务启动：");
            Schedule(() =>
            {
                Console.WriteLine(DateTime.Now+":任务执行");
                pushSms.Push();
                PushJPush.Push();

            }).ToRunNow().AndEvery(interval).Seconds();
        }

      
    }
    [HubName("ZhdMsgHub")]
    public class ZhdMsgHub : Hub
    {
        public static Dictionary<Guid, string> userConDic = new Dictionary<Guid, string>();


        public static void PushMsg(Guid[] userIds, string msg, IDictionary<string, object> param = null)
        {
            var userIdList = userIds.Where(p => userConDic.ContainsKey(p)).ToList();
            var conIds = userIdList.Select(p => userConDic[p]).ToArray();
            GlobalHost.ConnectionManager.GetHubContext<ZhdMsgHub>().Clients.Clients(conIds).ShowNotify(msg, param);
        
        }
        public static void RemoveUser(Guid userId) {
            if (userConDic.ContainsKey(userId))
            {
                userConDic.Remove(userId);
            }
        }
        public void SetName(Guid userId) {
            userConDic[userId] = Context.ConnectionId;
        }
        public void SendAll(string msg) {
            Clients.All.ShowNotify(msg);
        }
        public override Task OnReconnected()
        {

            return base.OnReconnected();
        }
        public override Task OnConnected()
        {
            if (ClientHelper.ClientInfo != null)
            {
                userConDic[ClientHelper.ClientInfo.Id] = Context.ConnectionId;
            }
            //var loginName = Guid.Parse(HttpContext.Current.Session[""] + "");
            //userConDic[loginName] = Context.ConnectionId;

             return base.OnConnected();
        }
        public override Task OnDisconnected(bool stopCalled)
        {

            return base.OnDisconnected(stopCalled);
        }
    }
}